<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use think\Db;

class Address extends Common {
    /**
     * @return mixed
     */
    public function claim() {
        $where['t1.delete_time'] = 0;

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if ($search_type == 'user_id') {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['t1.create_time'] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['t1.create_time'] = ['elt', strtotime($end)];
        }

        $state = input('state');
        if ($state || $state === '0') {
            $this->assign('state', $state);
            $where['t1.state'] = $state;
        }
        $andwhere = [];
        $hasuser  = input('hasuser');
        if ($hasuser || $hasuser === '0') {
            $this->assign('hasuser', $hasuser);
            $where['t1.user_id'] = $hasuser ? ['<>', 0] : 0;
        }

        $day  = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        $data = Db::name('user_claim_address')
            ->alias('t1')
            ->join('user t2', 't1.user_id = t2.id', 'left')
            ->where($where)
            ->where($andwhere)
            ->field('t1.*, t2.name username, t2.head_portrait')
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) use ($day) {
                $open_time         = $item['open_time'];
                $item['open_time'] = '';
                if ($open_time) {
                    $open_time    = explode('|', $open_time);
                    $open_time[0] = explode(',', $open_time[0]);
                    $daylen       = sizeof($open_time[0]);
                    $open_times   = [];
                    if ($daylen > 1) {
                        $next         = 1;
                        $index        = 0;
                        $open_times[] = [$day[0]];
                        while ($next) {
                            if ($open_time[0][$next - 1] == $open_time[0][$next] - 1) {
                                $open_times[$index][1] = $day[$open_time[0][$next] - 1];
                                if (isset($open_time[0][$next + 1])) {
                                    $next++;
                                } else {
                                    $next = 0;
                                }
                            } else {
                                $index++;
                                $open_times[$index][0] = $day[$open_time[0][$next] - 1];
                                if (isset($open_time[0][$next + 1])) {
                                    $next++;
                                } else {
                                    $next = 0;
                                }
                            }
                        }
                        foreach ($open_times as $key => $value) {
                            $open_times[$key] = implode('至', $open_times[$key]);
                        }
                    } else {
                        foreach ($open_time[0] as $key => $value) {
                            $open_times[] = $day[$value - 1];
                        }
                    }
                    $item['open_time'] = implode(',', $open_times) . ' ' . $open_time[1];
                }

                if ($item['user_id'] < 30000000) {
                    $item['oss_idx'] = 1;
                } else {
                    $user = Db::connect('database9')->name('user')->where(['id'=>$item['user_id']])->field('name username,head_portrait')->find();
                    if ($user) {
                        $user['from'] = '你好';
                        $item = array_merge($item, $user);
                    }
                    $item['oss_idx'] = 0;
                }
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * @param $id
     * @param $shenhe
     * @param $reason
     */
    public function shenheclaim($id, $shenhe, $reason = '') {
        $time          = time();
        $claim_address = Db::name('user_claim_address')->where(['id' => $id])->find();
        $result        = Db::name('user_claim_address')->where(['id' => $id])->update(['state' => $shenhe, 'reason' => $reason, 'update_time' => $time]);
        if ($result) {
            if ($claim_address['user_id']) {
                switch ((int) $shenhe) {
                case -1:
                    Privatechat::notice($claim_address['user_id'], "您认领的地点【" . $claim_address['name'] . "】被驳回" . ($reason ? "，驳回原因：" . $reason : "") . "，请重新编辑后再认领", '');
                    break;
                case 0:
                    Privatechat::notice($claim_address['user_id'], "您认领的地点【" . $claim_address['name'] . "】重新审核中", '');
                    break;
                case 1:
                    Privatechat::notice($claim_address['user_id'], "您认领的地点【" . $claim_address['name'] . "】审核通过", '');
                    break;
                }
            }
            return ['ret' => '操作成功'];
        } else {
            return ['err' => '操作失败'];
        }
    }

    /**
     * @return mixed
     */
    public function shenheclaimall() {
        if (request()->isAjax()) {
            $post   = input('post.');
            $shenhe = input('type');
            $reason = '';
            $time   = time();
            if (input('?post.delAll')) {
                $post    = $post['delAll'];
                $userids = [];
                foreach ($post as $k => $id) {
                    $claim_address = Db::name('user_claim_address')->where(['id' => $id])->find();
                    $userids[]     = $claim_address['user_id'];
                    if ($shenhe == 'del') {
                    } else {
                        if (!$claim_address['user_id']) {
                            continue;
                        }
                        switch ((int) $shenhe) {
                        case -1:
                            Privatechat::notice($claim_address['user_id'], "您认领的地点【" . $claim_address['name'] . "】被驳回" . ($reason ? "，驳回原因：" . $reason : "") . "，请重新编辑后再认领", '');
                            break;
                        case 0:
                            Privatechat::notice($claim_address['user_id'], "您认领的地点【" . $claim_address['name'] . "】重新审核中", '');
                            break;
                        case 1:
                            Privatechat::notice($claim_address['user_id'], "您认领的地点【" . $claim_address['name'] . "】审核通过", '');
                            break;
                        }
                    }
                }

                if ($shenhe == 'del') {
                    Db::name('user_claim_address')->where(['id' => ['in', $post]])->delete();
                } else {
                    $result = Db::name('user_claim_address')->where(['id' => ['in', $post]])->update(['state' => $shenhe, 'reason' => $reason, 'update_time' => $time]);
                }

                $data = ['ret' => '操作成功'];
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function redpacket() {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if ($search_type == 'user_id') {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['t1.pay_time'] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['t1.pay_time'] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['t1.pay_time'] = ['elt', strtotime($end)];
        }

        $status = input('status');
        if ($status || $status === '0') {
            $this->assign('status', $status);
            $where['t1.status'] = $status;
        }

        $paystate = input('paystate');
        if ($paystate || $paystate === '0') {
            $this->assign('paystate', $paystate);
            $where['t1.paystate'] = $paystate;
        }
        $data = Db::name('user_address_red_packet')
            ->alias('t1')
            ->join('user t2', 't1.user_id = t2.id', 'left')
            ->where($where)
            ->field('t1.*, t2.name username, t2.head_portrait')
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $item['price']      = floatval($item['price']);
                $item['totalprice'] = floatval($item['totalprice']);
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function redpackets() {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if ($search_type == 'user_id') {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['t1.time'] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['t1.time'] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['t1.time'] = ['elt', strtotime($end)];
        }

        $data = Db::name('user_address_redpacket_records')
            ->alias('t1')
            ->join('user t2', 't1.user_id = t2.id', 'left')
            ->where($where)
            ->field('t1.*, t2.name username, t2.head_portrait')
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function realtimesignconfig() {
        $data = Db::name('config_of_address_sign')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * @param $id
     * @param $data
     */
    public function realsignminchange($id, $data) {
        $col = Db::name('config_of_address_sign')->where(['id' => $id])->find();
        if ($col['max'] < $data) {
            return ['err' => '最小值不可大于最大值', 'val' => $col['min']];
        }
        $res = Db::name('config_of_address_sign')->where(['id' => $id])->setField('min', $data);
        if ($res) {
            return ['ret' => '修改成功'];
        }
        return ['err' => '修改失败', 'val' => $col['min']];
    }

    /**
     * @param $id
     * @param $data
     */
    public function realsignmaxchange($id, $data) {
        $col = Db::name('config_of_address_sign')->where(['id' => $id])->find();
        if ($col['min'] > $data) {
            return ['err' => '最大值不可小于最小值', 'val' => $col['max']];
        }
        $res = Db::name('config_of_address_sign')->where(['id' => $id])->setField('max', $data);
        if ($res) {
            return ['ret' => '修改成功'];
        }
        return ['err' => '修改失败', 'val' => $col['max']];
    }

    /**
     * @param $num
     */
    public function realsignconfigdele($num) {
        $res = Db::name('config_of_address_sign')->where(['num' => ['>=', $num]])->column('id');
        $res = Db::name('config_of_address_sign')->where(['id' => ['in', $res]])->delete();
        if ($res) {
            return ['ret' => '操作成功'];
        }
        return ['err' => '操作失败'];
    }

    public function realsignconfigadd() {
        $num = db('config_of_address_sign')->order('num desc')->value('num');
        $num = $num ? $num + 1 : 1;

        if (request()->isAjax()) {
            $post = input('post.');

            $data = [
                'num' => $num,
                'min' => $post['min'],
                'max' => $post['max'],
            ];

            $res  = db('config_of_address_sign')->insert($data);
            if ($res) {
                $data = ['ret' => '添加成功'];
            } else {
                $data = ['err' => '添加失败'];
            }
        } else {
            $this->assign('num', $num);
            $data = $this->fetch();
        }

        return $data;
    }
}